<template>
  <el-form :model="skuInfo" ref="skuFormRef" label-width="100px" class="sku-info" :rules="skuRules">
    <el-form-item label="SPU名称">
      <span>{{props.currentSpuInfo.spuName}}</span>
    </el-form-item>
    <el-form-item label="SKU名称" prop="skuName">
      <el-input v-model="skuInfo.skuName" placeholder="SKU名称"></el-input>
    </el-form-item>
    <el-form-item label="价格(元)" prop="price">
      <el-input-number v-model.number="skuInfo.price" :min="1" style="width:100%" :max="100" controls-position="right" />
    </el-form-item>
    <el-form-item label="重量(千克)" prop="weight">
      <el-input type="number" v-model="skuInfo.weight" :min="1" style="width:100%" :max="100" controls-position="right" />
    </el-form-item>
    <el-form-item label="SKU描述" prop="skuDesc">
      <el-input v-model="skuInfo.skuDesc" type="textarea" :rows="3" placeholder="SKU描述"></el-input>
    </el-form-item>
    <el-form-item label="平台属性" prop="skuAttrValueList">
      <el-row :gutter="10">
        <el-col v-for="(attr,index) in attrList" :key="attr.id" :xs="24" :sm="12" :md="8" :lg="8" :xl="8">
          <el-form-item :label="attr.attrName">
            <el-select placeholder="请选择" v-model="skuInfo.skuAttrValueList[index]" @change="clearAttrRules">
              <el-option v-for="attrValue in attr.attrValueList" :key="attrValue.id" :label="attrValue.valueName" :value="`${attr.id}:${attr.attrName}:${attrValue.id}:${attrValue.valueName}`" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form-item>
    <el-form-item label="销售属性" prop="skuSaleAttrValueList">
      <el-form-item v-for="(saleAttr,index) in spuSaleAttrList" :key="saleAttr.id" :label="saleAttr.saleAttrName">
        <el-select placeholder="请选择" v-model="skuInfo.skuSaleAttrValueList[index]" @change="clearSaleAttrRules">
          <el-option v-for="saleAttrValue in saleAttr.spuSaleAttrValueList" :label="saleAttrValue.saleAttrValueName" :key="saleAttrValue.id" :value="`${saleAttr.id}:${saleAttr.saleAttrName}:${saleAttrValue.id}:${saleAttrValue.saleAttrValueName}`" />
        </el-select>
      </el-form-item>
    </el-form-item>
    <el-form-item label="图片列表" prop="skuImageList">
      <el-table border :data="spuImageList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="60px"></el-table-column>
        <el-table-column label="图片">
          <template v-slot="{row}">
            <el-image style="width: 100px; height: 100px" :src="row.imgUrl" />
          </template>
        </el-table-column>
        <el-table-column label="名称" prop="imgName"></el-table-column>
        <el-table-column label="操作">
          <template v-slot="{row}">
            <el-button v-if="row.isDefault==='0'" type="primary" size="small" @click="setDefault(row)">设为默认项</el-button>
            <el-button v-else type="success" size="small" disabled>默认项</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submitSkuForm(skuFormRef)">保存</el-button>
      <el-button @click="emits('changeScene',1)">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<script lang="ts">
export default {
  name: 'SkuForm'
};
</script>

<script lang="ts" setup>
import { reqGetSpuImageList, reqGetSpuSaleAttrList } from '@/api/product/spu';
import { reqGetAttrListData } from '@/api/product/attr';
import { reqSaveSkuInfo } from '@/api/product/sku';
import { onMounted, ref, reactive } from 'vue';
import { useCategorySelectorInfoStore } from '@/stores/categorySelector';
import { ElMessage } from 'element-plus';
import type { FormInstance, FormRules } from 'element-plus';

const categoryStore = useCategorySelectorInfoStore();
const emits = defineEmits(['changeScene']);
const props = defineProps(['currentSpuInfo']);
const skuFormRef = ref<FormInstance>();

// 定义请求回来的数据
const spuImageList = ref([]);
const spuSaleAttrList = ref([]);
const attrList = ref([]);

// 添加skuInfo时用到的对应参数
const skuInfo = reactive({
  // spuName对应的id
  // spuId:0
  // sku名称
  skuName: '',
  // sku描述
  skuDesc: '',
  // 重量
  weight: '1',
  // 价格
  price: 3,
  // 是否上架
  // isSale:0,
  // 三级分类id
  category3Id: 0,
  // 默认图片的链接地址
  skuDefaultImg: '',
  // 选择的图片列表
  skuImageList: [],
  // 平台属性列表
  skuAttrValueList: [],
  // 销售属性列表
  skuSaleAttrValueList: []
});

// 使用自定义校验规则来验证图片列表是否有默认选项
const validateSkuImageList = (rule: any, value: any, callback: any) => {
  if (value.length < 3) return callback(new Error('图片至少选择三张'));
  // 再判断选择的三张图片中是否有默认项
  const flag = value.some(item => item.isDefault === '1');
  if (!flag) return callback(new Error('选择的图片中没有默认项，请添加默认项'));
  callback(); // 最终放行
};

// 书写校验规则
const skuRules = reactive<FormRules>({
  skuName: [
    { required: true, message: '请输入sku名称', trigger: 'blur' },
    {
      min: 1,
      max: 10,
      message: 'sku名称长度2--10之间',
      trigger: 'blur'
    }
  ],
  skuDesc: [{ required: true, message: '请输入sku描述', trigger: 'blur' }],
  price: [{ type: 'number', required: true, message: '价格不能为空', trigger: 'blur' }],
  weight: [{ required: true, message: '重量不能为空', trigger: 'blur' }],
  // 图片的自定义校验规则写法
  // skuImageList: [{ type: 'array', required: true, message: '请指示选择一张图片', trigger: 'change' }],
  skuImageList: [{ validator: validateSkuImageList, trigger: 'change' }],
  skuAttrValueList: [{ type: 'array', required: true, message: '请至少选择三项平台属性', trigger: 'change' }],
  skuSaleAttrValueList: [{ type: 'array', required: true, message: '请至少选择一项销售属性', trigger: 'change' }]
});

// 1.页面挂载完毕 就有发送请求 获取页面中需要展示的三种数据
// 三级导航下的平台属性  spu相关的销售属性  spu相关的图片列表
onMounted(async () => {
  console.log(props, props.currentSpuInfo);
  const id = props.currentSpuInfo.id;

  const [responseSpuImageList, responseSpuSaleAttrList, responseAttrList] = await Promise.allSettled([
    reqGetSpuImageList(id),
    reqGetSpuSaleAttrList(id),
    reqGetAttrListData({
      category1Id: categoryStore.category1Id,
      category2Id: categoryStore.category2Id,
      category3Id: categoryStore.category3Id
    })
  ]);

  if (responseSpuImageList.status === 'fulfilled') {
    spuImageList.value = responseSpuImageList.value.map(item => {
      return {
        ...item,
        isDefault: '0' // 额外再次添加一个属性，用于区分是否默认项
      };
    });
  }
  if (responseSpuSaleAttrList.status === 'fulfilled') {
    spuSaleAttrList.value = responseSpuSaleAttrList.value;
  }
  if (responseAttrList.status === 'fulfilled') {
    attrList.value = responseAttrList.value;
  }
});

// 2.给图片列表设置默认选中项
const setDefault = row => {
  // 2.1先将所有的图片设置为非默认
  spuImageList.value.forEach(item => (item.isDefault = '0'));
  // 2.2再将当前被单击的哪一项设置为默认
  row.isDefault = '1';
  // 2.3收集默认图片链接地址
  skuInfo.skuDefaultImg = row.imgUrl;
  // 2.4清空校验规则
  const imgArr = skuInfo.skuImageList;
  if (imgArr.length >= 3 && imgArr.some(item => item.isDefault === '1')) {
    skuFormRef.value?.clearValidate(['skuImageList']);
  }
};

// 3.获取选择的图片列表
const handleSelectionChange = val => {
  skuInfo.skuImageList = val;
};

// 4.清除平台属性的校验规则
const clearAttrRules = () => {
  const length = skuInfo.skuAttrValueList.filter(Boolean).length;
  if (length >= 3) {
    skuFormRef.value?.clearValidate(['skuAttrValueList']);
  }
};

// 5.清空销售属性的校验规则
const clearSaleAttrRules = () => {
  skuFormRef.value?.clearValidate(['skuSaleAttrValueList']);
};

// 6. 格式化数据
const formatData = () => {
  // 重新处理一下平台属性数据
  skuInfo.skuAttrValueList = skuInfo.skuAttrValueList.filter(Boolean).map((item: string) => {
    const [attrId, attrName, valueId, valueName] = item.split(':');
    return {
      attrId,
      attrName,
      valueId,
      valueName
    };
  });

  // 销售属性也要处理一下
  skuInfo.skuSaleAttrValueList = skuInfo.skuSaleAttrValueList.filter(Boolean).map((item: string) => {
    const [saleAttrId, saleAttrName, saleAttrValueId, saleAttrValueName] = item.split(':');
    return {
      saleAttrId,
      saleAttrName,
      saleAttrValueId,
      saleAttrValueName
    };
  });

  skuInfo.spuId = props.currentSpuInfo.id;
  skuInfo.category3Id = props.currentSpuInfo.category3Id;
};

// 添加skuInfo对象
const submitSkuForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      // console.log('submit!');
      formatData();
      // 发送请求
      await reqSaveSkuInfo(skuInfo);
      ElMessage.success('添加sku数据成功');
      emits('changeScene', 1); // 跳转至skuList列表页
    } else {
      console.log('error submit!', fields);
    }
  });
};
</script>

<style lang="scss" scoped>
.sku-info {
  .el-select {
    margin-bottom: 10px;
  }
}
</style>